package com.pxst.sys.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pxst.sys.entity.UserCurrencyEntity;
import com.pxst.sys.mapper.UserCurrencyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.pxst.config.JWTConfig;
import com.pxst.entity.LoginUser;
import com.pxst.resp.ApiResp;
import com.pxst.resp.LoginResp;
import com.pxst.sys.entity.AuthorityEntity;
import com.pxst.sys.entity.RoleEntity;
import com.pxst.sys.entity.UserEntity;
import com.pxst.sys.mapper.AuthorityMapper;
import com.pxst.sys.mapper.RoleMapper;
import com.pxst.sys.req.LoginReq;
import com.pxst.sys.service.LoginService;
import com.pxst.sys.service.UserService;
import com.pxst.utils.JWTTokenUtil;
import com.pxst.utils.RedisUtils;

/** 
* @author yangxy
* @version 创建时间：2023年7月26日 下午5:23:37 
*/
@Service
public class LoginServiceImpl implements LoginService {
	@Autowired
	private RedisUtils redisUtils;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private AuthorityMapper authorityMapper;
	@Autowired
	private BCryptPasswordEncoder bCryptPasswordEncoder;
	@Autowired
	private UserCurrencyMapper userCurrencyMapper;

	@Override
	@SuppressWarnings("unchecked")
	public ApiResp<LoginResp> login(LoginReq loginParam) {
		// TODO Auto-generated method stub
//		if(!redisUtils.hasKey(loginParam.getUuid())) {
//			return ApiVo.codeError("验证码已过期");
//		}
		
//		int code = (int) redisUtils.get(loginParam.getUuid());
//		redisUtils.del(loginParam.getUuid());
//		if(loginParam.getCode() != code) {
//			return ApiVo.codeError("验证码错误");
//		}
		
		UserEntity userEntity = userService.getOne(new QueryWrapper<UserEntity>().lambda().eq(UserEntity::getUserName, loginParam.getUserName()));
		if(ObjectUtils.isEmpty(userEntity)) {
			return ApiResp.authError("用户名或密码错误");
		}
		
		if(!bCryptPasswordEncoder.matches(loginParam.getPassword(), userEntity.getPassword())) {
			return ApiResp.authError("用户名或密码错误");
		}
		
		List<RoleEntity> roleList = Lists.newArrayList();
		List<AuthorityEntity> authList;
		if(userEntity.getIsAdmin() == 1) {//超级管理员拥有所有权限
			authList = authorityMapper.selectList(new QueryWrapper<AuthorityEntity>().lambda().eq(AuthorityEntity::getIsUse, 1));
		}else {
			roleList = roleMapper.getHaveRoleByUserId(userEntity.getId());
			authList = authorityMapper.getHaveAuthByUserId(userEntity.getId());
		}
		List<String> roleCodeList = roleList.stream().map(RoleEntity::getRoleCode).collect(Collectors.toList());
		
		List<String> authCodeList = authList.stream().map(AuthorityEntity::getAuthorityCode).collect(Collectors.toList());

		// 查询关联币种
		List<UserCurrencyEntity> currencyEntityList = userCurrencyMapper.selectList(new LambdaQueryWrapper<UserCurrencyEntity>().eq(UserCurrencyEntity::getUserId, userEntity.getId()));
		List<String> currencyList = currencyEntityList.stream().map(UserCurrencyEntity::getCurrency).collect(Collectors.toList());

		LoginUser loginUser = new LoginUser();
		loginUser.setUserId(userEntity.getId());
		loginUser.setPassword(userEntity.getPassword());
		loginUser.setUsername(userEntity.getUserName());
		loginUser.setAuthCods(authCodeList);
		loginUser.setRoleCodes(roleCodeList);
		loginUser.setIsAdmin(userEntity.getIsAdmin());
		loginUser.setCurrencyList(currencyList);
		
		String createAccessToken = JWTTokenUtil.createAccessToken(loginUser);
		
		LoginResp loginDto = new LoginResp();
		loginDto.setAccessToken(createAccessToken);
		redisUtils.set(createAccessToken, loginUser,2*60*60);
		return ApiResp.sucess(loginDto);
	}

	@Override
	@SuppressWarnings("unchecked")
	public ApiResp<String> loginout(HttpServletRequest request) {
		// TODO Auto-generated method stub
		String token = request.getHeader(JWTConfig.tokenHeader);
		if(!StringUtils.isEmpty(token)) {
			redisUtils.del(token);
		}
		return ApiResp.sucess();
	}

}
